package com.thoughtworks.stafftimetable.parser;

import com.thoughtworks.stafftimetable.domain.Assignment;
import com.thoughtworks.stafftimetable.domain.Consultant;
import com.thoughtworks.stafftimetable.domain.ScheduledAssignment;
import static com.thoughtworks.stafftimetable.util.DateUtil.DATE_FORMATTER_FOR_SOURCE_DATA;

import java.text.ParseException;
import java.util.List;
import java.util.StringTokenizer;

public class SourceDataLineParser {
    public List<Consultant> parse(List<Consultant> consultants, String csvLine) throws ParseException {
        StringTokenizer tokenizer = new StringTokenizer(csvLine, ",");
        String account = tokenizer.nextToken();
        String project = tokenizer.nextToken();
        tokenizer.nextToken(); // Skip country
        String name = tokenizer.nextToken();
        tokenizer.nextToken(); // Skip country;
        tokenizer.nextToken(); // Skip role;
        String startDate = getDateIfTokenExists(tokenizer);
        String endDate = getDateIfTokenExists(tokenizer);
        Consultant consultant = addConsultantIfTheyAreNotAlreadyInTheList(consultants, name);
        if (startDate != null) {
            Assignment assignment = new ScheduledAssignment(account, project, 
                                            DATE_FORMATTER_FOR_SOURCE_DATA.parse(startDate),
                                            DATE_FORMATTER_FOR_SOURCE_DATA.parse(endDate));
            consultant.addAssignment(assignment);
        }
        return consultants;
    }

    private Consultant addConsultantIfTheyAreNotAlreadyInTheList(List<Consultant> consultants, String name) {
        Consultant consultant = findConsultantInList(consultants, name);
        if (consultant == null) {
            consultant = new Consultant(name);
            consultants.add(consultant);
        }

        return consultant;
    }

    private Consultant findConsultantInList(List<Consultant> consultants, String name) {
        for (Consultant consultant : consultants) {
            if (name.equals(consultant.getName())) {
                return consultant;
            }
        }
        return null;
    }

    private String getDateIfTokenExists(StringTokenizer tokenizer) throws ParseException {
        if (tokenizer.hasMoreTokens()) {
            return tokenizer.nextToken();
        }
        return null;
    }
}
